package com.zhaoyu.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaoyu.common.fastdfs.FastDFSClient;
import com.zhaoyu.model.common.dtos.PageResponseResult;
import com.zhaoyu.model.common.dtos.ResponseResult;
import com.zhaoyu.model.common.enums.AppHttpCodeEnum;
import com.zhaoyu.model.media.dtos.WmMaterialDto;
import com.zhaoyu.model.media.pojos.WmMaterial;
import com.zhaoyu.model.media.pojos.WmNewsMaterial;
import com.zhaoyu.utils.threadlocal.WmThreadLocalUtils;
import com.zhaoyu.wemedia.mapper.WmMaterialMapper;
import com.zhaoyu.wemedia.mapper.WmNewsMaterialMapper;
import com.zhaoyu.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IService 实现类（泛型：M 是 mapper 对象，T 是实体）
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient; // FastDFS工具类

    @Value("${fileServerUrl}")
    private String fileServerUrl; // 图片服务器地址

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadImage(MultipartFile file) {
        try {
            if (file == null) { // 判断文件是否为空
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || "".equals(originalFilename)) { // 判断文件名是否为空
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String uploadFile = fastDFSClient.uploadFile(file); // 上传图片到FastDFS服务器
            String picUrl = fileServerUrl + uploadFile; // 图片服务器地址 + FastDFS服务器上传图片路径
            WmMaterial wmMaterial = new WmMaterial(); // 创建自媒体图文素材信息表
            wmMaterial.setUrl(uploadFile); // 图片路径
            wmMaterial.setCreatedTime(new Date()); // 创建时间
            wmMaterial.setIsCollection((short) 1); // 0:未收藏 1:已收藏
            wmMaterial.setType((short) 0); // 0图片/1视频
            wmMaterial.setUserId(WmThreadLocalUtils.getUserId()); // 自媒体用户ID
            save(wmMaterial); // 保存自媒体图文素材信息表
            return ResponseResult.okResult(picUrl); // 返回图片路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @Override
    public ResponseResult findImage(WmMaterialDto wmMaterialDto) {
        /**
         * 请求参数是null，默认查第一页
         */
        if (wmMaterialDto == null){
            wmMaterialDto = new WmMaterialDto();
        }
        /**
         * 获取默认的分页信息
         */
        wmMaterialDto.checkParam();
        /**
         * 条件
         */
        Page page = new Page<WmMaterial>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 获取当前登录的用户
        Integer userId = WmThreadLocalUtils.getUserId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, userId);
        // 是否收藏
        if (wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection() == 1) { // 0:未收藏 1:已收藏
            /**
             * 测试(postman)：http://localhost:6002/wemedia/api/v1/material/find_picture(带token)
             *      "page": 1,
             *      "size": 10,
             *      "isCollection": 1
             */
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection()); // WmMaterial::getIsCollection：是否收藏
        }
        // 按照日期倒叙排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage result = page(page, lambdaQueryWrapper);
        /**
         * 当前页(默认第一页)：getCurrent
         * 当前页总页数：getSize
         * 总条数：getTotal
         * 分页对象记录列表：getRecords
         * 封装结果
         */
        ResponseResult responseResult = new PageResponseResult((int) result.getCurrent(), (int) result.getSize(), (int) result.getTotal());
        // 为每个图片加上前缀
        List<WmMaterial> records = result.getRecords();
        records = records.stream().map(item ->{
            item.setUrl(fileServerUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(records);
        return responseResult;
    }

    @Override
    public ResponseResult deleteImage(Integer id) {
        // 1、检查参数
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2、判断当前图片是否被引用
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId, id); // WmNewsMaterial::getMaterialId：素材ID
        if (wmNewsMaterialMapper.selectCount(lambdaQueryWrapper) > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前图片被引用");
        }
        // 3、删除FastDFS中的图片
        String fileId = wmMaterial.getUrl().replace(fileServerUrl, "");
        try {
            fastDFSClient.deleteFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 4、删除数据库中的图片
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateIsCollectionById(Integer id, Short isCollection) {
        // 1、检查参数
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2、更新状态
        Integer userId = WmThreadLocalUtils.getUserId(); // 获取当前用户信息
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,isCollection)
                .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}